local weiguang = fk.CreateSkill {
  name = "th_weiguang"
}

---@type TrigSkelSpec<fun(self: TriggerSkill, event: DamageEvent, target: ServerPlayer, player: ServerPlayer, data: DamageData):any>
local spec = {
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(weiguang.name) and not data.prevented and data.from and data.from ~= data.to then
      local another = player == data.from and data.to or data.from
      if not player:canPindian(another) then return end
      local damage_events = player.room.logic:getEventsOfScope(GameEvent.Damage, 2, function(e)
        local damage = e.data
        return not data.prevented and damage.from and data.from ~= damage.to and (data.from == player or data.to == player)
      end, Player.HistoryTurn)
      return #damage_events == 1 and damage_events[1].data == data
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local another = player == data.from and data.to or data.from
    if not another then return end
    if room:askToSkillInvoke(player, {
      skill_name = weiguang.name,
      prompt = "#th_weiguang-invoke::" .. another.id
    }) then
      local anim = data.to == player and "defensive" or "offensive"
      event:setCostData(self, { tos = { another }, anim_type = anim })
      return true
    end 
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = event:getCostData(self).tos[1]
    if not to then return end
    local pindian = player:pindian({ to }, weiguang.name)
    if pindian.results[to].winner == player then
      data:preventDamage()
      room:addPlayerMark(player, "@th_weiguang")
    end
  end
}

weiguang:addEffect(fk.DetermineDamageCaused, spec)
weiguang:addEffect(fk.DetermineDamageInflicted, spec)
weiguang:addEffect(fk.DamageCaused, {
  anim_type = "offensive",
  is_delay_effect = true,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:getMark("@th_weiguang") ~= 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local num = player:getMark("@th_weiguang")
    room:setPlayerMark(player, "@th_weiguang", 0)
    data:changeDamage(num)
  end,
})
weiguang:addEffect(fk.PindianResultConfirmed, {
  anim_type = "negative",
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(weiguang.name) and data.winner and data.winner ~= player
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    player.room:askToDiscard(player, {
      min_num = 1,
      max_num = 1,
      skill_name = weiguang.name
    })
  end,
})

Fk:loadTranslationTable{
  ["th_weiguang"] = "威光",
  [":th_weiguang"] = "当你每回合首次对其他角色造成或受到其他角色造成的伤害时，你可以与其拼点：若你赢，防止此伤害并令你下次造成的伤害+1。当你拼点输时，你弃置一张牌。",

  ["#th_weiguang-invoke"] = "威光：你可以与 %dest 拼点：若你赢，防止此伤害并令你下次造成的伤害+1",

  ["@th_weiguang"] = "威光＋"
}

return weiguang
